/**
 * 
 */
package main.org.form.action;

import java.sql.Timestamp;
import java.util.LinkedHashMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import main.org.model.Utils;

import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import org.compiere.dsr.DSR_Cell;
import org.compiere.dsr.DSR_DataCollection;
import org.compiere.model.I_BPM_FormValues;
import org.compiere.model.MBPMForm;
import org.compiere.model.MBPMFormValues;
import org.compiere.model.MBPMProject;
import org.compiere.model.MBPMSubs;
import org.compiere.model.X_BPM_FormCode;
import org.compiere.model.X_C_Project;
import org.compiere.util.DB;
import org.compiere.util.Env;

/**
 * @author V.Sokolov
 * 
 */
public class FormBP extends Forms implements ServletRequestAware,
		ServletResponseAware {

	/**
	 * 
	 */
	private static final long serialVersionUID = -7222019810593858920L;
	/* */
	public static final String sessionKey = "formBP";

	public static String getNBSP(int count) {

		String nbsp = "";
		int i = 0;
		while (i < count) {
			nbsp += "&nbsp;&nbsp;&nbsp;";
			i++;
		}
		return nbsp;
	}

	DSR_DataCollection collection;
	private HttpServletRequest request;
	private HttpServletResponse response;
	private int projectID;
	private int ProjectSubID;
	private int userID;
	public int BPM_VersionBudget_ID;

	LinkedHashMap<Integer, String> projectList = new LinkedHashMap<Integer, String>();

	/* 
	 */
	@Override
	public String execute() throws Exception {

		StringBuilder err = new StringBuilder();

		setMessageError(err.toString());
		if (err.length() != 0)
			return NONE;
		Forms fo = (Forms) session.get(Forms.sessionKey);
		fo.setPage(Utils.TEMPLATE_SECOND);
		session.put(Forms.sessionKey, fo);
		setPage(Utils.TEMPLATE_SECOND);
		setBPM_VersionBudget_ID(fo.getBudget().getBPM_VersionBudget_ID());
		setAD_Client_ID(fo.AD_Client_ID);

		super.setBudget();
		DSR_DataCollection collection = new DSR_DataCollection(getFormID(),
				getProjectID(), AD_Org_ID, AD_Client_ID, getProjectSubID());
		setCollection(collection);
		session.put(FormBP.sessionKey, this);

		MBPMForm form = new MBPMForm(Env.getCtx(), getFormID(), null);
		if (form.getBPM_FormCode().getCategoryName()
				.equals(X_BPM_FormCode.CATEGORYNAME_Profitability)
				&& getProjectSubID() == 0) {

			setProjectList();
			if (getProjectList().size() == 0)
				err.append("Не найден проект для ДЗО <br />");

			setMessageError(err.toString());
			if (err.length() != 0)
				return NONE;

			return X_BPM_FormCode.CATEGORYNAME_Profitability;
		}

		return SUCCESS;
	}

	public DSR_DataCollection getCollection() {
		return collection;
	}


	public LinkedHashMap<Integer, String> getProjectList() {
		return projectList;
	}

	public int getProjectSubID() {
		return ProjectSubID;
	}

	public HttpServletResponse getServletResponse() {
		return response;
	}

	public int getUserID() {
		return userID;
	}

	/*
	 */
	@Override
	public String input() throws Exception {

		StringBuilder err = new StringBuilder();

		FormBP foBP = (FormBP) session.get(FormBP.sessionKey);
		
		setCollection(foBP.getCollection());
		setAD_Client_ID(foBP.AD_Client_ID);
		setMessageError(err.toString());
		if (err.length() != 0)
			return NONE;

		int counts = 0;
		if (getProjectSubID() != 0)
			counts = MBPMFormValues.countValues(projectID, getFormID(),
					AD_Org_ID, getProjectSubID());
		else
			counts = MBPMFormValues.countValues(projectID, getFormID(),
					AD_Org_ID);

		if (counts != 0) {
			updateValues(foBP);
		} else {
			insertValues(foBP);
		}

		return INPUT;
	}

	private int insertValues(FormBP fb) {

		DSR_Cell cell = null;
		MBPMFormValues formValues = null;
		String value = "";
		int count = 1;
		int row = 1;
		int col = 0;
		for (int i = 0; i < collection.size(); i++) {
			col = 0;
			for (int j = 0; j < collection.getRow(i).size(); j++) {
				cell = collection.getRow(i).getCell(j);
				if (!cell.isRow) {
					value = request.getParameter("cell_Row" + row + "_Col"
							+ col);
					formValues = new MBPMFormValues(Env.getCtx(), 0, null);
					formValues.set_ValueOfColumn("AD_Client_ID", AD_Client_ID);
					formValues.setAD_Org_ID(AD_Org_ID);
					formValues.setBPM_Form_ID(getFormID());
					formValues.setBPM_FormCell_ID(cell.getBPM_FormCell_ID());
					formValues.setBPM_FormLine_ID(cell.getBPM_FormLine_ID());
					formValues.setBPM_FormColumn_ID(cell.getBPM_FormColumn_ID());
					formValues.setBPM_VersionBudget_ID(fb.BPM_VersionBudget_ID);
					formValues.setBPM_Project_ID(getProjectID());
					if (getProjectSubID() != 0)
						formValues.setBPM_SubsProject_ID(getProjectSubID());
					formValues.setCellValue(value);
					formValues.setAlternateValue("");
					formValues.saveEx();
				}
				col++;
			}
			count++;
			row++;
		}
		return count;
	}

	private void loadProjects() {
		MBPMProject project = new MBPMProject(Env.getCtx(), BPM_Project_ID, null);
		this.projectList.put(BPM_Project_ID, project.getName());
		setDefaultProjectID(BPM_Project_ID);
	}

	public HttpServletRequest request() {
		return request;
	}

	public void setCollection(DSR_DataCollection collection) {
		this.collection = collection;
	}

	public void setBPM_VersionBudget_ID(int BPM_VersionBudget_ID) {
		this.BPM_VersionBudget_ID = BPM_VersionBudget_ID;
	}

	public void setProjectList() {
		loadProjects();
	}

	public void setProjectSubID(int projectSubID) {
		ProjectSubID = projectSubID;
	}

	public void setServletRequest(HttpServletRequest request) {
		this.request = request;
	}

	public void setServletResponse(HttpServletResponse response) {
		this.response = response;
	}

	public void setUserID(int userID) {
		this.userID = userID;
	}

	private boolean updateValues(FormBP fb) {
		StringBuffer sql = new StringBuffer("");
		StringBuffer value = new StringBuffer("");
		StringBuffer upd = new StringBuffer("update "
				+ I_BPM_FormValues.Table_Name);
		StringBuffer where = new StringBuffer(" where BPM_Project_ID="
				+ getProjectID() + "\n and AD_Client_ID=" + AD_Client_ID 
				+ "\n and AD_Org_ID=" + AD_Org_ID
				+ "\n and BPM_Form_ID=" + getFormID());



		DSR_Cell cell = null;
		Timestamp updated = new Timestamp(System.currentTimeMillis());


		for (int i = 0; i < collection.size(); i++) {

			for (int j = 0; j < collection.getRow(i).size(); j++) {
				cell = collection.getRow(i).getCell(j);
				if ((cell==null)||(cell.isRow)) continue;
				value.setLength(0);
				value.append(request.getParameter("cell_Row" + (i+1) + "_Col" + j));
				if ((value.toString().equals(cell.getValue()))) continue;
				sql.setLength(0);
				sql.append(upd).append(" set cellValue='");
				sql.append(value+ "'");
				sql.append(" , updated='" + updated + "'"+ " , updatedby="+Env.getCtx().getProperty("#AD_User_ID"));
				sql.append(where).append(
						"\n and BPM_FormLine_ID=" + cell.getBPM_FormLine_ID()
								+ "\n and BPM_FormColumn_ID="
								+ cell.getBPM_FormColumn_ID());
				DB.executeUpdate(sql.toString(), null);
				cell.setValue(value.toString());
			}

		}
		return true;
	}

	public int getProjectID() {
		return projectID;
	}

	public void setProjectID(int projectID) {
		this.projectID = projectID;
	}
	
}
